package cn.iocoder.yudao.module.project.controller.admin.websocket;

import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

public class WebSocketSessionManager {
    private static final ConcurrentHashMap<String, WebSocketSession> sessions =
            new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, String> userSessionMap =
            new ConcurrentHashMap<>();

    // 添加会话
    public static void addSession(String userId, WebSocketSession session) {
        sessions.put(userId, session);
        userSessionMap.put(session.getId(), userId);
    }

    // 移除会话
    public static void removeSession(WebSocketSession session) {
        String userId = userSessionMap.get(session.getId());
        if (userId != null) {
            sessions.remove(userId);
            userSessionMap.remove(session.getId());
        }
    }

    // 获取会话
    public static WebSocketSession getSession(String userId) {
        return sessions.get(userId);
    }

    // 获取所有会话
    public static ConcurrentHashMap<String, WebSocketSession> getAllSessions() {
        return sessions;
    }

    // 获取在线用户数量
    public static int getOnlineCount() {
        return sessions.size();
    }

    // 根据会话ID获取用户ID
    public static String getUserIdBySessionId(String sessionId) {
        return userSessionMap.get(sessionId);
    }
}
